package com.pig4cloud.pig.floor.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.floor.dto.PropertyFloorDto;
import com.pig4cloud.pig.floor.entity.PropertyFloor;
import com.pig4cloud.pig.floor.service.FloorService;
import com.pig4cloud.pig.floor.vo.PropertyFloorVo;
import com.pig4cloud.pig.propertyroom.entity.PropertyRoom;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/floor" )
@Tag(description = "floor" , name = "楼层管理" )
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class FloorController{
	@Autowired
	private FloorService floorService;

	@GetMapping("/page")
	public R getFloorPage(@ParameterObject Page page, @ParameterObject PropertyFloorDto propertyFloorDto) {
		Page<PropertyFloorVo> result = floorService.wrapperPage(page, propertyFloorDto);
		return R.ok(result);
	}

	@GetMapping("/getFloor")
	public R getFloor(@RequestParam Long unitId) {
		QueryWrapper<PropertyFloor> wrapper = new QueryWrapper<>();
		wrapper.eq("unit_id", unitId);
		return R.ok(floorService.list(wrapper));
	}

	@GetMapping("/getFloorById")
	public R getFloorById(@RequestParam Long floorId) {
		return R.ok(floorService.getFloorById(floorId));
	}

	@PostMapping("/addFloor")
	public R addFloor(@RequestBody PropertyFloor floorEntity) {
		QueryWrapper<PropertyFloor> wrapper = new QueryWrapper<>();
		wrapper.eq("floor_name", floorEntity.getFloorName());
		wrapper.eq("floor_number", floorEntity.getFloorNumber());
		wrapper.eq("unit_id", floorEntity.getUnitId());
		if (floorService.count(wrapper) > 0) {
			return R.failed("楼层已存在");
		}
		return R.ok(floorService.save(floorEntity));
	}

	@DeleteMapping("/deleteFloor")
	public R deleteFloor(@RequestParam Long[] ids) {
		PropertyRoom[] propertyRooms = floorService.selectRoomByFloorId(ids);
		if (propertyRooms.length > 0) {
			return R.failed("该楼层下有房间存在，不能删除");
		}
		return R.ok(floorService.removeByIds(Arrays.asList(ids)));
	}

	@PutMapping("/updateFloor")
	public R updateFloor(@RequestBody PropertyFloor propertyFloor) {
		System.out.println(propertyFloor);
		PropertyFloor floor = floorService.checkFloorByNumberAndName(propertyFloor);
		if (floor != null) {
			return R.failed("楼层已存在");
		}
		return R.ok(floorService.updateById(propertyFloor));
	}
}
